package cn.lgp6.ziyou_util.music.controller;
import cn.lgp6.ziyou_util.music.entity.dto.MusicMessageDTO;
import com.alibaba.fastjson.JSON;
import jdk.nashorn.internal.ir.IfNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/music/data")
public  class MusicWebSocketController {
    private static Logger logger=LoggerFactory.getLogger(MusicWebSocketController.class);

    //记录用户人数
    public static volatile  Map<Session,String> userMap=new ConcurrentHashMap<>();

    public volatile AtomicInteger integer=new AtomicInteger(0);
    public static volatile String src="1449339372";
    public static volatile String musicName="庸人自扰之";
    public static volatile List<Map<String,String>> queue=new ArrayList<>();

    public synchronized static void sendText(Session session, MusicMessageDTO messageDTO, String methodName,boolean log) {
        synchronized (session){
           if (log){
               logger.info(methodName+"调用发送方法");
           }
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(messageDTO));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public synchronized void onOpen(Session session) {

        MusicMessageDTO musicMessageDTO=new MusicMessageDTO();
        musicMessageDTO.setMusicName(musicName);
        musicMessageDTO.setCurrent(src);
        if (queue.size()<=0){
            initQueue();
        }
        musicMessageDTO.setQueue(queue);
        if (userMap.size()<=0){
            logger.info(session.getId()+"成为房间主人,"+userMap.size());
            //这个用户是房间主人
            userMap.put(session,"owner");
            musicMessageDTO.setType("owner");
            musicMessageDTO.setMsg("您已进入大厅,并成为大厅主人");
        }else{
            userMap.put(session,String.valueOf(integer.addAndGet(1)));
            musicMessageDTO.setType("normal");
            musicMessageDTO.setMsg("您已进入大厅");
        }


        sendText(session,musicMessageDTO,"onopen",true);

        logger.info("新用户{"+session.getId()+"}进入,当前用户人数:"+userMap.size());
    }

    /*初始化播放队列*/
    private void initQueue() {
        Map<String,String> map=new HashMap<>();
        map.put("id","1449339372");
        map.put("name","庸人自扰之");
        queue.add(map);

        Map<String,String> map2=new HashMap<>();
        map2.put("id","1840861309");
        map2.put("name","万疆");
        queue.add(map2);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public static synchronized void onClose(Session session) {
        if (userMap.get(session).equals("owner")){
            Session sessionMin=null;
            for (Session session1 : userMap.keySet()) {
                if (session1!=session){
                    if (sessionMin==null){
                        sessionMin=session1;
                    }
                    if (Integer.parseInt(userMap.get(session1))<Integer.parseInt(userMap.get(sessionMin))){
                        sessionMin=session1;
                    }
                }
            }
            if (sessionMin!=null){
                MusicMessageDTO musicMessageDTO=new MusicMessageDTO();
                musicMessageDTO.setType("newOwner");
                musicMessageDTO.setMsg("大厅主人退出房间,您成为新的大厅主人");
                userMap.put(sessionMin,"owner");
                sendText(sessionMin,musicMessageDTO,"onclose 77",true);
                for (Session session1 : userMap.keySet()) {
                    if (session1!=session&&session1!=sessionMin){
                        musicMessageDTO.setType("changeOwner");
                        musicMessageDTO.setMsg("前一位大厅主人离开房间,新的大厅主人产生,将重新同步播放进度");
                        sendText(session1,musicMessageDTO,"onclose 85",true);
                    }
                }
            }
            logger.info("用户{"+session.getId()+"}退出大厅,重新选举大厅主人");

        }else{
            logger.info("用户{"+session.getId()+"}退出大厅");
        }
        userMap.remove(session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public synchronized void onMessage(Session session,String message) {
        String[] split = message.split(",");
        if (split.length>=3){
            if (!split[0].equals("current")){
                logger.info("用户{"+session.getId()+"}发送信息:"+message);
            }
            if (split[0].equals("current")&&split[1].equals("owner")&&userMap.get(session).equals("owner")){
/*                logger.info("主人时间:"+split[2]);
                logger.info("主人状态:"+split[3]);*/
                for (Session session1 : userMap.keySet()) {
                    if (session1!=session){
                        MusicMessageDTO messageDTO=new MusicMessageDTO();
                        messageDTO.setType("time");
                        messageDTO.setCurrent(String.valueOf(Math.ceil(Double.parseDouble(split[2]))));
                        messageDTO.setPlay(split[3].equals("true"));
                        sendText(session1,messageDTO,"onmessage 91",false);
                    }
                }
            }
            if (split[0].equals("pause")&&split[1].equals("owner")){
                if (userMap.get(session).equals("owner")){
                    MusicMessageDTO messageDTO=new MusicMessageDTO();
                    messageDTO.setType("pause");
                    messageDTO.setMsg("大厅主人暂停了播放");
                    for (Session session1 : userMap.keySet()) {
                        if (session1!=session){
                            sendText(session1,messageDTO,"onmessage 131",true);
                        }
                    }
                }
            }
            if (split[0].equals("play")&&split[1].equals("owner")){
                if (userMap.get(session).equals("owner")){
                    MusicMessageDTO messageDTO=new MusicMessageDTO();
                    messageDTO.setType("play");
                    messageDTO.setMsg("大厅主人播放了音乐");
                    for (Session session1 : userMap.keySet()) {
                        if (session1!=session){
                            sendText(session1,messageDTO,"onmessage 145",true);
                        }
                    }
                }
            }
            if (split[0].equals("switch")&&split[1].equals("owner")){
                if (userMap.get(session).equals("owner")){
                    MusicMessageDTO messageDTO=new MusicMessageDTO();
                    queue.remove(0);
                    if (queue.size()<=0)
                        initQueue();
                    messageDTO.setType("switch");
                    messageDTO.setMsg("大厅主人切换音乐为:"+queue.get(0).get("name"));
                    messageDTO.setCurrent(queue.get(0).get("id"));
                    messageDTO.setMusicName(queue.get(0).get("name"));
                    messageDTO.setQueue(queue);
                    logger.info("大厅主人切换音乐:"+queue.get(0).get("name")+",url:"+queue.get(0).get("id"));
                    musicName=queue.get(0).get("name");
                    src=queue.get(0).get("id");
                    for (Session session1 : userMap.keySet()) {
                            sendText(session1,messageDTO,"onmessage 160",true);
                    }
                }
            }
            if (split[0].equals("addQueue")){
                String id=split[2];
                String name=split[3];
                Map<String,String> map=new HashMap<>();
                map.put("id",id);
                map.put("name",name);
                queue.add(map);
                MusicMessageDTO changeQueueDTO=new MusicMessageDTO();
                changeQueueDTO.setQueue(queue);
                changeQueueDTO.setType("changeQueue");
                changeQueueDTO.setMsg("播放队列已更新");
                for (Session session1 : userMap.keySet()) {
                    sendText(session1,changeQueueDTO,"onmessage 207",true);
                }
            }
            if (split[0].equals("removeQueue")&&split[1].equals("owner")){
                if (userMap.get(session).equals("owner")){
                    int index=-1;
                    for (int i=0;i<queue.size();i++) {
                        if (queue.get(i).get("id").equals(split[2])){
                            index=i;
                        }
                    }
                    if (index>0) {
                        queue.remove(index);
                    }
                    if (queue.size()<=0){
                        initQueue();
                    }
                        MusicMessageDTO changeQueueDTO=new MusicMessageDTO();
                        changeQueueDTO.setQueue(queue);
                        changeQueueDTO.setType("changeQueue");
                        changeQueueDTO.setMsg("播放队列已更新");
                        for (Session session1 : userMap.keySet()) {
                            sendText(session1,changeQueueDTO,"onmessage 207",true);
                        }
                    }
            }
        }

    }

    @OnError
    public synchronized void onError(Session session, Throwable error) {
        logger.info("异常"+error.getLocalizedMessage());
    }

}
